package cn.sinokj.party.chineseFourParty.utils.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.sinokj.party.chineseFourParty.utils.logs.Logger;


/**
 * Http最终调用,封装httpClient
 * @author azzbcc E-mail: azzbcc@sina.com
 * @version 创建时间：2015年11月4日 下午1:36:06
 */
public class HttpUtils {

	private static Logger logger = Logger.getLogger();
	
	public static final String post(String url) {
		return post(url, (List<NameValuePair>) null);
	}

	public static final String post(String url, JSONObject json) {
		List<NameValuePair> param = new ArrayList<NameValuePair>();
		param.add(new BasicNameValuePair("json", json.toString()));
		return post(url, param);
	}

	public static final String post(String url, Map<String, String> map) {
		List<NameValuePair> param = getForm(map);
		return post(url, param);
	}

	public static final String post(String url, List<String> fileList, Map<String, String> paramMap) {
		MultipartEntity mpEntity = new MultipartEntity();
		for (int i = 0; i < fileList.size(); i++) {
			ContentBody contentBody = new FileBody(new File(fileList.get(i)));
			mpEntity.addPart("file" + i, contentBody);
		}
		for (Map.Entry<String, String> entry : paramMap.entrySet()) {
			try {
				StringBody stringBody = new StringBody(entry.getValue(), Charset.forName("UTF-8"));
				mpEntity.addPart(entry.getKey(), stringBody);
			} catch (UnsupportedEncodingException e) {
				logger.e(e);
			}
		}
		logger.d("参数:" + paramMap + ", " + fileList);
		return post(url, mpEntity);
	}
	
	
	private static final String post(String url, List<NameValuePair> param) {
		HttpEntity entity = null;
		if (null != param) {
			try {
				entity = new UrlEncodedFormEntity(param, HTTP.UTF_8);
				logger.d("参数:" + param.toString());
			} catch (UnsupportedEncodingException e) {
				logger.e(e);
			}
		}
		return post(url, entity);
	}
	
	/**
	 * post方式请求数据
	 * 
	 * @param url 请求的url
	 * @param entity
	 * @return String 返回json数据
	 */
	private static final String post(String url, HttpEntity entity) {
		String result = null;
		try {
			HttpPost request = new HttpPost(url);
			if (null != entity) {
				request.setEntity(entity);
			}
			DefaultHttpClient client = MyHttpClient.getSaveHttpClient();
			logger.d("请求:" + url);
			synchronized (client) {
				HttpResponse response = client.execute(request);
				logger.d("response.getStatusLine().getStatusCode()", response.getStatusLine().getStatusCode());
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					result = EntityUtils.toString(response.getEntity(), "UTF-8").trim();
					logger.d("http result json", result);
				}
			}
		} catch (ClientProtocolException e) {
			logger.e(e);
		} catch (IOException e) {
			logger.e(e);
		}
		return result;
	}

	public static final String getHttp(String url) {
		String result = null;
		try {
			HttpGet request = new HttpGet(url);
			DefaultHttpClient client = MyHttpClient.getSaveHttpClient();
			logger.d("请求 : " + url);
			synchronized (client) {
				HttpResponse response = client.execute(request);
				logger.d("response.getStatusLine().getStatusCode()", response.getStatusLine().getStatusCode());
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					result = EntityUtils.toString(response.getEntity(), "UTF-8").trim();
					logger.d("http result json", result);
				}
			}
		} catch (ClientProtocolException e) {
			logger.e(e);
		} catch (IOException e) {
			logger.e(e);
		}
		return result;
	}
	
	/**
	 * get请求数据 返回json
	 * 
	 * @param url 请求的url
	 * @return String 返回json数据
	 */
	public static final String get(String url) {
		String result = null;
		try {
			final HttpGet request = new HttpGet(url);
			DefaultHttpClient client = MyHttpClient.getSaveHttpClient();
			logger.d("请求 : " + url);
			synchronized (client) {
				HttpResponse response = client.execute(request);
				logger.d("response.getStatusLine().getStatusCode()", response.getStatusLine().getStatusCode());
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					result = EntityUtils.toString(response.getEntity(), "UTF-8").trim();
					logger.d("http result json", result);
				}
			}
		} catch (ClientProtocolException e) {
			logger.e(e);
		} catch (IOException e) {
			logger.e(e);
		}
		return result;
	}
	
	/**
	 * 包装http请求参数， 提交的form就两种key：action和json 所以Map<String,String>了 无参数时返回“”
	 * 
	 * @param params
	 * @return
	 */
	private static final List<NameValuePair> getForm(Map<String, String> params) {
		List<NameValuePair> form = null;
		if (null != params && params.size() > 0) {
			form = new ArrayList<NameValuePair>();
			final Iterator<Map.Entry<String, String>> iter = params.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry<String, String> entry = iter.next();
				final String key = entry.getKey();
				final String val = entry.getValue();

				if (val != null) {
					form.add(new BasicNameValuePair(key, val));
				}
			}
		}
		return form;
	}
}
